﻿using SkiaSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace QiAdmin.Core.Utils
{
    public class CaptchaUtil
    {
        public static byte[] CreateCaptcha(string code)
        {
            Random random = new();
            //前景色
            var colors = new[] { SKColors.Black, SKColors.Red, SKColors.DarkBlue, SKColors.Green, SKColors.Orange, SKColors.Brown, SKColors.DarkCyan, SKColors.Purple };

            //背景色
            var backcolors = new[] { SKColors.AntiqueWhite, SKColors.WhiteSmoke, SKColors.FloralWhite };

            //字体
            var fonts = new[] { "Cantarell" };
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                fonts = new[] { "宋体" };
            }

            using var image2d = new SKBitmap(code.Length * 20, 30, SKColorType.Bgra8888, SKAlphaType.Premul);
            using var canvas = new SKCanvas(image2d);
            //背景
            canvas.DrawColor(backcolors[random.Next(0, backcolors.Length - 1)]);
            //样式
            using var drawStyle = new SKPaint();

            //填充验证码到图片
            for (int i = 0; i < code.Length; i++)
            {
                drawStyle.IsAntialias = true;
                drawStyle.TextSize = 16;
                var font = SKTypeface.FromFamilyName(fonts[random.Next(0, fonts.Length - 1)], SKFontStyleWeight.SemiBold, SKFontStyleWidth.ExtraCondensed, SKFontStyleSlant.Upright);
                drawStyle.Typeface = font;
                drawStyle.Color = colors[random.Next(0, colors.Length - 1)];

                canvas.DrawText(code[i].ToString(), (i + 1) * 16, 20, drawStyle);
            }
            //干扰线
            for (int i = 0; i < 6; i++)
            {
                drawStyle.Color = colors[random.Next(colors.Length)];
                drawStyle.StrokeWidth = 1;
                canvas.DrawLine(random.Next(0, code.Length * 15), random.Next(0, 60), random.Next(0, code.Length * 16), random.Next(0, 30), drawStyle);
            }

            using var img = SKImage.FromBitmap(image2d);
            using var p = img.Encode(SKEncodedImageFormat.Png, 100);
            using var ms = new MemoryStream();
            //保存到流
            p.SaveTo(ms);

            byte[] arr = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(arr, 0, (int)ms.Length);
            return arr;

        }
    }
}
